在程式開發中,錯誤是無法避免的。
例如:

try
{
    int number = int.Parse("ABC"); // 嘗試把文字轉數字,會失敗
    Console.WriteLine(number);
}
catch (Exception ex)
{
    Console.WriteLine($"發生錯誤:{ex.Message}");
}
結果:
發生錯誤:輸入字串的格式不正確。
有時候需要針對不同類型的例外做不同處理。
例如:
try
{
    string input = null;
    Console.WriteLine(input.Length); // 會丟 NullReferenceException
}
catch (NullReferenceException ex)
{
    Console.WriteLine("物件尚未初始化,不能使用。");
}
catch (FormatException ex)
{
    Console.WriteLine("格式錯誤,無法轉換。");
}
catch (Exception ex)
{
    Console.WriteLine($"其他錯誤:{ex.Message}");
}
Exception ex 要放在最後?因為 Exception 是「所有例外的父類別」。
catch (Exception ex),它會攔住所有錯誤,後面的更精準的 catch 就不會執行。finally 代表「不管有沒有例外,一定會執行」。常用來釋放資源,例如關閉檔案、釋放連線。
try
{
    Console.WriteLine("開始計算");
    int x = 10 / 0; // 除以零錯誤
}
catch (DivideByZeroException)
{
    Console.WriteLine("不能除以零!");
}
finally
{
    Console.WriteLine("這段一定會執行,適合放清理程式碼。");
}
輸出:
開始計算
不能除以零!
這段一定會執行,適合放清理程式碼。
假設我們要從字典 Dictionary<string, decimal> 查股票價格。
如果輸入錯誤的股票代號,會發生 KeyNotFoundException。
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        Dictionary<string, decimal> prices = new Dictionary<string, decimal>
        {
            { "2330", 1265m },
            { "2303", 45.7m }
        };
        try
        {
            Console.WriteLine($"2330 價格:{prices["2330"]}");
            Console.WriteLine($"9999 價格:{prices["9999"]}"); // KeyNotFoundException
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("查無此股票代號");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"其他錯誤:{ex.Message}");
        }
        finally
        {
            Console.WriteLine("查詢結束。");
        }
    }
}
要記得:
今天我們學會了:
try-catch 的基本用法Exception ex 要放在最後finally 適合放清理程式碼